package com.example.loadbalance;

import com.alibaba.fastjson.JSON;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.loadbalance.AbstractLoadBalance;

import java.util.List;
import java.util.Random;

public class MyLoadbalance extends AbstractLoadBalance {

    /**
     * 测试自定义负载均衡一定要多个提供者，否则不进入该方法，是在消费端做负载均衡
     * @param list
     * @param url
     * @param invocation
     * @param <T>
     * @return
     */
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> list, URL url, Invocation invocation) {
        System.out.println("cosumemer MyLoadbalance:"+ JSON.toJSONString(url));
        int a = new Random().nextInt(list.size());
        System.out.println("cosumemer MyLoadbalance index:"+ a);
        return list.get(a);
    }
}
